<?php
// +----------------------------------------------------------------------
// | BhAdmin [ BhAdmin匠心打造，我们相信，每个伟大的软件都有一个伟大的故事 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2023 https://www.bhadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BhAdmin并不是自由软件，未经许可不能去掉BhAdmin相关版权
// +----------------------------------------------------------------------
// | Author: BAIHU  <admin@bhadmin.cn>
// +----------------------------------------------------------------------
namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\ConfigService;

class ConfigLogic extends BaseLogic
{

    public static function getList()
    {
        $configList = ConfigService::getAllList([['mark', '=', 1]], ['*'], ['sort' => 'asc']);
        return message($configList);
    }

    public static function edit()
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;

        if (!isset($data['name']) || empty($data['name'])) {
            throw new ApiException('请输入配置名称');
        }

        if (!isset($data['code']) || empty($data['code'])) {
            throw new ApiException('请输入配置编码');
        }
        if (!isset($data['sort']) || empty($data['sort'])) {
            throw new ApiException('请输入排序');
        }
        $save['name'] = trim($data['name']);
        $save['sort'] = $data['sort'];
        $save['code'] = $data['code'] ?? '';
        $save['note'] = $data['note'] ?? '';
        unset($data['id']);
        if ($id == 0) {
            // code重复性验证
            $count = ConfigService::getUserCountByWhere([["code", '=', $save['code']], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的配置编码');
            }
            ConfigService::add($save);
        } else {
            $count = ConfigService::getUserCountByWhere([["code", '=', $save['code']], ["id", "<>", $id], ["mark", "=", 1]]);
            if ($count > 0) {
                throw new ApiException('系统中已存在相同的配置项值');
            }
            ConfigService::save($save, $id);
        }
        return message();

    }

    public static function delete()
    {
        $ids = request()->post('id');
        if (!$ids) throw new ApiException('记录ID不能为空');
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        ConfigService::delete($ids);
        return message();
    }


}
